package cc.shacocloud.mirage.restful.http;

import io.vertx.core.file.FileSystem;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.RoutingContext;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 基于{@link MultipartFileUpload}的默认实现
 */
public class MultipartFileUploadImpl implements MultipartFileUpload {
    
    private final Map<String, MultipartFile> fileMap;
    
    public MultipartFileUploadImpl(RoutingContext context) {
        List<FileUpload> fileUploads = context.fileUploads();
        
        Map<String, MultipartFile> fileMap;
        if (fileUploads == null) {
            fileMap = Collections.emptyMap();
        } else {
            // 使用 vertx的文件系统
            FileSystem fs = context.vertx().fileSystem();
            fileMap = fileUploads.stream()
                    .collect(Collectors.toMap(FileUpload::name, f -> new MultipartFileImpl(f, fs)));
        }
        
        this.fileMap = Collections.unmodifiableMap(fileMap);
    }
    
    @Override
    public boolean isEmpty() {
        return fileMap.isEmpty();
    }
    
    @Override
    public int size() {
        return fileMap.size();
    }
    
    @Override
    public MultipartFile get() throws IllegalArgumentException {
        if (fileMap.size() == 1) {
            return fileMap.entrySet().iterator().next().getValue();
        }
        throw new IllegalArgumentException("上传的文件数量为 '" + size() + "' ，文件数量不等于1无法直接获取！");
    }
    
    @Nullable
    @Override
    public MultipartFile get(String name) {
        return fileMap.get(name);
    }
    
    @Override
    public Map<String, MultipartFile> files() {
        return fileMap;
    }
}
